package com.project.srtp.service.impl;

import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.project.srtp.common.biz.UserContextHolder;
import com.project.srtp.common.config.FileStorageProperties;
import com.project.srtp.common.convention.ClientException;
import com.project.srtp.common.convention.ServiceException;
import com.project.srtp.common.utils.JwtTokenProvider;
import com.project.srtp.dao.entity.UserDO;
import com.project.srtp.dao.mapper.UserMapper;
import com.project.srtp.dto.req.UserLoginReqDTO;
import com.project.srtp.dto.req.UserRegisterReqDTO;
import com.project.srtp.dto.resp.*;
import com.project.srtp.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.transaction.Transactional;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Collections;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.project.srtp.common.constant.RedisCacheConstant.LOCK_USER_REGISTER_KEY;

@Service
@RequiredArgsConstructor
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements UserService {

    private final RBloomFilter<String> usernameBloomFilter;
    private final RedissonClient redissonClient;
    private final FileStorageProperties fileStorageProperties;
    private final JwtTokenProvider jwtTokenProvider;


    public UserLoginRespDTO login(UserLoginReqDTO param) {
        LambdaQueryWrapper<UserDO> queryWrapper = Wrappers.lambdaQuery(UserDO.class)
                .eq(UserDO::getUsername, param.getUsername())
                .eq(UserDO::getDeleteFlag, 0);
        UserDO userDO = baseMapper.selectOne(queryWrapper);

        if (userDO == null) {
            throw new ClientException("用户名或密码错误");
        }

        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        if (!encoder.matches(param.getPassword(), userDO.getPassword())) {
            throw new ClientException("用户名或密码错误");
        }

        String token = jwtTokenProvider.generateToken(userDO.getId(), userDO.getUsername(), Collections.emptyList());

        return UserLoginRespDTO.builder()
                .userId(userDO.getUserId())
                .id(userDO.getId())
                .username(userDO.getUsername())
                .token(token)
                .expireTime(System.currentTimeMillis() +
                        jwtTokenProvider.getValidityInMilliseconds())
                .tokenType("Bearer")
                .build();
    }


    @Transactional
    public UserRegisterRespDTO registerBasic(UserRegisterReqDTO param) {
        UserDO userDO = UserDO.builder()
                .username(param.getUsername())
                .userId(UUID.randomUUID().toString())
                .password(new BCryptPasswordEncoder().encode(param.getPassword()))
                .company(param.getCompany())
                .creditCode(param.getCreditCode())
                .companyType(param.getCompanyType())
                .industry(param.getIndustry())
                .contactPerson(param.getContactPerson())
                .contactPhone(param.getContactPhone())
                .build();
        if (existsUsername(param.getUsername())) {
            throw new ClientException("用户名已存在");
        }
        RLock lock = redissonClient.getLock(LOCK_USER_REGISTER_KEY + param.getUsername());
        try {
            if (lock.tryLock(2, 10, TimeUnit.SECONDS)) {
                try {
                    if (!save(userDO)) {
                        throw new ServiceException("用户保存失败");
                    }
                    usernameBloomFilter.add(param.getUsername());
                    return new UserRegisterRespDTO(userDO.getId(), userDO.getUserId());
                } catch (DuplicateKeyException ex) {
                    throw new ClientException("用户名已存在");
                }
            }
            throw new ClientException("用户名已存在");
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new ClientException("注册请求被中断");
        } finally {
            if (lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
    }


    @Transactional
    public void uploadBusinessLicense(Long userId, MultipartFile file) {
        // 1. 参数校验
        if (file.isEmpty()) {
            throw new ClientException("文件不能为空");
        }

        // 2. 验证用户状态
        UserDO user = this.getById(userId);
        if (user == null || user.getStatus() != 0) {
            throw new ClientException("无效的用户状态");
        }

        // 3. 文件验证
        validateFile(file);


        try {
            // 4. 生成存储路径
            String fileName = generateFileName(file.getOriginalFilename());
            Path storagePath = Paths.get(fileStorageProperties.getUploadDir(), fileName);

            // 5. 确保目录存在
            Files.createDirectories(storagePath.getParent());

            // 6. 存储文件
            Files.copy(file.getInputStream(), storagePath, StandardCopyOption.REPLACE_EXISTING);

            // 7. 更新用户信息
            user.setBusinessLicensePath(storagePath.toString());
            user.setStatus(1L);
            if (!updateById(user)) {
                Files.deleteIfExists(storagePath);
                throw new ServiceException("用户信息更新失败");
            }
        } catch (IOException e) {
            throw new ServiceException("文件存储失败: " + e.getMessage());
        }
    }

    public void logicDeleteUser(Long id) {
        update(new LambdaUpdateWrapper<UserDO>()
                .eq(UserDO::getId, id)
                .set(UserDO::getDeleteFlag, 1)
                .set(UserDO::getCancelTime, System.currentTimeMillis()));
    }

    @Override
    public UserInfoRespDTO getUserInfo() {
        Long id = UserContextHolder.getUserId();
        LambdaQueryWrapper<UserDO> queryWrapper = Wrappers.lambdaQuery(UserDO.class)
                .eq(UserDO::getId, id)
                .eq(UserDO::getDeleteFlag, 0);
        UserDO userDO = baseMapper.selectOne(queryWrapper);
        if (userDO == null) {
            throw new ClientException("用户不存在");
        }
        UserInfoRespDTO result = new UserInfoRespDTO();
        BeanUtils.copyProperties(userDO, result);
        return result;
    }

    @Override
    public IPage<FriendsRespDTO> getFriends() {
        Long id = UserContextHolder.getUserId();
        Page<UserDO> page = new Page<>(1, 10);
        UserDO currentUser = baseMapper.selectById(id);
        if (currentUser == null) {
            throw new RuntimeException("当前用户不存在");
        }
        String companyCode = currentUser.getCreditCode();
        LambdaQueryWrapper<UserDO> queryWrapper = Wrappers.lambdaQuery(UserDO.class)
                .eq(UserDO::getCreditCode, companyCode)
                .ne(UserDO::getId, id)
                .eq(UserDO::getDeleteFlag, 0);

        IPage<UserDO> userPage = baseMapper.selectPage(page, queryWrapper);
        IPage<FriendsRespDTO> dtoPage = new Page<>();
        dtoPage.setCurrent(userPage.getCurrent());
        dtoPage.setSize(userPage.getSize());
        dtoPage.setTotal(userPage.getTotal());

        dtoPage.setRecords(userPage.getRecords().stream().map(user -> {
            FriendsRespDTO dto = new FriendsRespDTO();
            dto.setUserId(user.getUserId());
            dto.setUsername(user.getUsername());
            return dto;
        }).collect(Collectors.toList()));

        return dtoPage;
    }

    @Override
    public String getUserIdByUsername(String username) {
        LambdaQueryWrapper<UserDO> queryWrapper = Wrappers.lambdaQuery(UserDO.class)
                .eq(UserDO::getUsername, username)
                .eq(UserDO::getDeleteFlag, 0);
        UserDO userDO = baseMapper.selectOne(queryWrapper);
        return userDO.getUserId();
    }

    private void validateFile(MultipartFile file) {
        // 文件类型校验
        String contentType = file.getContentType();
        if (!fileStorageProperties.getAllowedTypes().contains(contentType)) {
            throw new ClientException("仅支持JPEG/PNG/PDF格式");
        }

        // 文件大小校验
        if (file.getSize() > fileStorageProperties.getMaxSize()) {
            throw new ClientException("文件大小不能超过"
                    + (fileStorageProperties.getMaxSize() / 1024 / 1024) + "MB");
        }
    }

    private String generateFileName(String originalName) {
        String ext = StringUtils.getFilenameExtension(originalName);
        return UUID.randomUUID() + "." + ext;
    }

    public UserRespDTO getByUsername(String username) {
        LambdaQueryWrapper<UserDO> queryWrapper = Wrappers.lambdaQuery(UserDO.class)
                .eq(UserDO::getUsername, username)
                .eq(UserDO::getDeleteFlag, 0);
        UserDO userDo = baseMapper.selectOne(queryWrapper);
        if (userDo == null) {
            throw new ClientException("用户名不存在");
        }
        UserRespDTO result = new UserRespDTO();
        BeanUtils.copyProperties(userDo, result);
        return result;
    }

    public UserRespDTO getByID(Long id) {
        LambdaQueryWrapper<UserDO> queryWrapper = Wrappers.lambdaQuery(UserDO.class)
                .eq(UserDO::getId, id)
                .eq(UserDO::getDeleteFlag, 0);
        UserDO userDO = baseMapper.selectOne(queryWrapper);
        if (userDO == null) {
            throw new ClientException("用户名不存在");
        }
        UserRespDTO result = new UserRespDTO();
        BeanUtils.copyProperties(userDO, result);
        return result;
    }

    public boolean existsUsername(String username) {
        if (usernameBloomFilter.contains(username)) {
            LambdaQueryWrapper<UserDO> queryWrapper = Wrappers.lambdaQuery(UserDO.class)
                    .eq(UserDO::getUsername, username)
                    .eq(UserDO::getDeleteFlag, 0);
            UserDO userDO = baseMapper.selectOne(queryWrapper);
            return userDO == null;
        }
        return false;
    }
}
